<?php
namespace App\Services;
use App\Models\StudentCourseModel;
use App\Models\StudentSignModel;
use App\Models\ClassCourseModel;
use App\Models\CourseArrangeModel;
use App\Models\ClassStudentModel;
use App\Models\StudentModel;
use App\Models\TeacherModel;
use App\Tools\SignTemplate;
use App\Tools\Fun;


class CourseService {
    private const SIGN_RESULT = [ '未签到', '正常', '迟到', '请假', '旷课' ];
    public static function sign($arrangeCourseId, $courseId, $studentId, $result, $courseNum = 0, $forceSign = false) {
        
        if (!$studentId || !$arrangeCourseId) {
            return "缺少参数";
        }

        $courseArrange = CourseArrangeModel::find($arrangeCourseId);
        // $courseId = $courseArrange->course_id;
        $classId = $courseArrange->class_id;
        $data = [
            'company_id' => $courseArrange->company_id,
            'arrange_id' => $arrangeCourseId,
            'student_id' => $studentId,
            'course_id' => $courseId,
            'class_id' => $classId,
            'date' => $courseArrange->date,
            'time' => $courseArrange->time
        ];
        $sign = StudentSignModel::where($data)->first();
        if ($sign) {
            if($result == 0) { // 重置
                self::resetSign($sign->id, $arrangeCourseId);
                return true;
            }

            if($forceSign) { // 强制签到
                self::resetSign($sign->id, $arrangeCourseId);
            } else {
                return '该学员已签到';
            }
        }

        $courseOrders = StudentCourseModel::where('student_id', $studentId)
            ->where('course_id', $courseId)
            ->where('pay_status', 1)
            ->where('valid_end_date', '>=', date('Y-m-d'))
            ->whereRaw('learned_num < (course_num + send_num)')
            ->orderBy('id', 'desc')
            ->limit(2)
            ->get();

        $courseOrderNum = $courseOrders->count();
        if ($courseOrderNum == 0) {
            return '学员未报名或课程已过期';
        }

        $preOrder = $courseOrderNum == 2 ? $courseOrders[1] : null;
        $lastOrder = $courseOrders[0]; // 最后一笔课程订单
        $courseMoney = 0;
        $courseNum = $courseNum?: $courseArrange->course_num;

        if($result == 1 || $result == 2) {
            
            // 如果学员购买了两次课程，那么在扣课时，需要先把之前未扣完的先扣除
            // 先检查是否有未扣完的课程
            
            $preRemainCourseNum = $preOrder ? ($preOrder->course_num + $preOrder->send_num - $preOrder->learned_num) : 0; // 剩余的课程数
            if($preRemainCourseNum > 0) {
                $preOrderCourseNum = $preOrder->course_num + $preOrder->send_num; // 总课程数
                $courseMoney = $preRemainCourseNum * ($preOrder->pay_price / $preOrderCourseNum); // 本次消课金额
                $preOrder->learned_num += $preRemainCourseNum; // 已学习课程数增加
            }
            
            if($courseNum > $preRemainCourseNum) { // 如果前面的订单剩余课时不足本次总课时，则考虑扣后面的课程
                $tempCourseNum = $courseNum - $preRemainCourseNum;
                $lastOrderCourseNum = $lastOrder->course_num + $lastOrder->send_num; // 最后一笔课程订单的总课程数
                $courseMoney += $tempCourseNum * ($lastOrder->pay_price / $lastOrderCourseNum); // 本次消课金额
                $lastOrder->learned_num += $tempCourseNum; // 已学习课程数增加
            }
        }
         // 保存签到信息
         $sign = new StudentSignModel();
         $sign->fill($data);
         $sign->result = $result;
         $sign->course_num = $courseNum;
         $sign->course_money = $courseMoney;
         $sign->student_course_id = $preOrder ? $preOrder->id : $lastOrder->id;
         $sign->save();

        if($result == 1 || $result == 2) {
            // 修改学员课程的总的消耗课时
            if($preOrder) $preOrder->save();
            $lastOrder->save();

            // 修改学生在改班级所消耗的课时
            ClassStudentModel::where('student_id', $studentId)
            ->where('course_id', $courseId)
            ->where('class_id', $classId)
            ->increment('learned_num', $courseNum);

            // 增加到场人数统计
            $courseArrange->attend_student_num += 1; // 增加到场人数统计
            $courseArrange->total_course_num += $courseNum; // 累计消耗课时统计    
        }

        $courseArrange->status = 1;
        $courseArrange->save();

        // 通过模版消息通知家长签到情况
        $student = StudentModel::find($studentId);
        if($student->parent_wx_id  && !Fun::is_windows()) {
            $remainCourseNum = $lastOrder->course_num + $lastOrder->send_num - $lastOrder->learned_num;
            $signResult = self::SIGN_RESULT[intval($result)];
            $signTemplate = new SignTemplate($student->parent_wx_id, $student->name, $lastOrder->course_name, $signResult, $remainCourseNum, '');
            $signTemplate->send();
        }
        return true;
    }

    public static function resetSign($id, $arrangeCourseId) {
        $sign = StudentSignModel::find($id);
        $courseNum = $sign->course_num;
        if($sign->result == 1 ||  $sign->result == 2) {
            // 减去班级上课的课时消耗统计
            ClassStudentModel::where('student_id', $sign->student_id)
            ->where('course_id', $sign->course_id)
            ->where('class_id', $sign->class_id)
            ->decrement('learned_num', $courseNum);

            // 减去该学生的总课时消耗统计
            $studentCourse = StudentCourseModel::where('student_id', $sign->student_id)
            ->where('course_id', $sign->course_id)
            ->orderBy('id', 'desc')
            ->first();

            $studentCourse->learned_num -= $courseNum;
            $studentCourse->save();

            // 减去本次排课表的课时消耗统计
            CourseArrangeModel::where('id', $arrangeCourseId)->decrement('total_course_num', $courseNum);

            // 减去到场人数统计
            CourseArrangeModel::where('id', $arrangeCourseId)->decrement('attend_student_num', 1);

            // 重置薪酬 等下次再计算
            CourseArrangeModel::where('id', $arrangeCourseId)->update(['commission' => null]);
        }

        $sign->delete();
    }
}